package feng.demo.controller.mer;

import feng.demo.dao.LargefileDao;
import feng.demo.entity.*;
import feng.demo.service.BreedService;
import feng.demo.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mer/type")
public class MerTypeController {
    @Autowired
    TypeService typeService;
    @Autowired
    BreedService breedService;
    @Autowired
    LargefileDao largefileDao;

    @GetMapping("/del/{id}")
    public String del(@PathVariable("id")Integer typeid){
//        删除类型
        int del = typeService.del(typeid);
        List<Breeds> breeds = breedService.findAlls();
        return new XJson(200,"删除成功",breeds).toString();
    }

    @GetMapping("/findByBreed")
    public String  findByBreed(){
//        查找品种做下拉框
        List<Breed> breeds = breedService.findAll();
        return new XJson(200,"",breeds).toString();
    }

    @GetMapping("/findById/{id}")
    public String findByid(@PathVariable("id")Integer typeid){
//        查找更改类型
        Map<String,Object> map=new HashMap<>();
        List<Breed> breeds = breedService.findAll();
        Type type = typeService.findById(typeid);
        map.put("breed",breeds);
        map.put("type",type);
        return new XJson(200,"",map).toString();
    }

    @PostMapping("/add")
    public String add(Type type, MultipartFile img){
        if (img==null){

            int add = typeService.add(type);

        }else {
            Largefile largefile = new Largefile();
            try {
                largefile.setFilename(img.getOriginalFilename());
                byte[] bytes=img.getBytes();
                largefile.setContent(bytes);
            }catch (Exception e){

            }
            Integer add = largefileDao.add(largefile);
            type.setPic(add);
            typeService.add(type);
        }
        return new XJson(200,"添加成功","").toString();
    }

    @PostMapping("/update")
    public String update(Type type,MultipartFile img){
        if (img==null){
            typeService.update(type);
        }else {
            largefileDao.delete(type.getPic());
            Largefile largefile = new Largefile();
            try {
                largefile.setFilename(img.getOriginalFilename());
                byte[] bytes=img.getBytes();
                largefile.setContent(bytes);
            }catch (Exception e){

            }
            Integer add = largefileDao.add(largefile);
            type.setPic(add);
            typeService.update(type);
        }
        return new XJson(200,"修改成功","").toString();
    }

}
